// ------------------------------------------------ user script ------------------------------------------------
include_shared('ajaxian');
include_shared('encFunc');

window.onload = initializePage;

var enc_key = false;

function initializePage() {
	setupLoginForm().onsubmit = handleFormSUbmission;
}

function handleFormSUbmission() {
	$('submit_button').disabled = 1;
	$('loading-login-form-overlay').style.display = 'block';
	submit_login($('login_customer_id').value, enc_pass($('login_password').value));
	return false;
}

function setupLoginForm() {

	var loginForm = createForm(rootUrl+'authenticate', {'id':'login'});

	var helpmess = CE('p');
	helpmess.innerHTML = 'Sign in with your Game City Customer ID and password.'
	AC(loginForm, helpmess);

	AC(loginForm, createLabel('Customer ID'));
	AC(loginForm, createInput({'id':'login_customer_id', 'type':'text', 'name':'customer_id'}));
	AC(loginForm, createLabel('Password'));
	AC(loginForm, createInput({'id':'login_password', 'type':'password', 'name':'password'}));
	var spanInputRemMe = CE('span');
	AC(spanInputRemMe, createInput({'type':'checkbox', 'checked':'checked'}));
	AC(spanInputRemMe, document.createTextNode('Remember me on this computer'));
	AC(loginForm, spanInputRemMe);
	AC(loginForm, createInput({'id':'submit_button', 'type':'submit', 'value':'Submit'}));


	var loginFormContainer = $('login-noscript').parentNode;
	AC(loginFormContainer, loginForm);
	AC(loginFormContainer, createLink('Forgot your password?', 'recoverpass.c'));


	var overlay = createDiv({'id':'loading-login-form-overlay', 'className':'show-80'});
	overlay.style.width = loginForm.offsetWidth+'px';
	overlay.style.left = loginForm.offsetLeft+'px';
	overlay.style.height = loginForm.offsetHeight+8+'px';
	overlay.style.top = loginForm.offsetTop+'px';
	overlay.style.display = 'none';


	var spin = new Image();
	spin.id = 'spin';
	spin.src = rootUrl + 'images/shared/loading.gif';
	AC(overlay, spin);

	AC(loginFormContainer, overlay);
	return loginForm;
}

function enc_pass(pass) {
	var key = getcookie('IllucidateLogin')
	enc_key = (key) ? key : hex_sha1(Math.random() + 'apples');
	pass = hex_sha1(pass + 'only mahees shou*&^ld know th$4$is!')
	return hex_sha1(enc_key + pass);
}

function submit_login(uname, encpass) {
	var post = 'customerId=' + encodeURI(uname) + '&password=' + encpass + '&enctdKey=' + enc_key;
	makeAJAXRequest($('login').action, loginSubmissionResponse, null, {'responseType':'text', 'post':post});
}

function loginSubmissionResponse(res) {
	results = res.split('|!|');
	if (results[0] == 'true') { return window.location = rootUrl + results[1]; }
	$('login_customer_id').style.border = '2px solid yellow';
	$('login_password').style.border = '2px solid yellow';
	$('loading-login-form-overlay').style.display = 'none';
	$('submit_button').disabled = false;
	return false;
}